<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">检测项目</label>
        <el-input v-model="query.testItem" clearable placeholder="检测项目" style="width: 185px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"/>
        <el-select v-model="query.graphType" clearable filterable
                   placeholder="请选择" style="width: 185px;" class="filter-item" @change="crud.toQuery">
          <el-option
            v-for="item in dict.graph_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <label class="el-form-item-label">产品型号</label>
        <el-input v-model="query.productCode" clearable placeholder="产品型号" style="width: 185px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"/>
        <rrOperation :crud="crud"/>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission"/>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="50%">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="SPC名称" prop="name">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="产品型号" prop="productCode">
            <el-select v-model="form.productCode" style="width: 370px" filterable placeholder="请选择"
                       @change="getEquipment" ref="selection">
              <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.productName"
                :value="item.productCode">
                <span style="float: left">{{ item.productName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.productCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <!--<el-form-item label="产品名称">-->
          <!--<el-input v-model="form.productName" style="width: 370px;" />-->
          <!--</el-form-item>-->
          <el-form-item label="设备" prop="equipmentCode">
            <el-select v-model="form.equipmentCode" style="width: 370px" filterable placeholder="请选择"
                       @change="getTestItem">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.deviceName"
                :value="item.deviceCode">
                <span style="float: left">{{ item.deviceName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deviceCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检测项目" prop="testItem">
            <!--<el-input v-model="form.testItem" style="width: 370px;" />-->
            <el-select v-model="form.testItem" clearable placeholder="请选择" style="width: 370px;" @change="setBound">
              <el-option
                v-for="item in parameter"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="样本容量" prop="capacity">
            <!--<el-input v-model="form.capacity" style="width: 370px;" />-->
            <el-input-number size="medium" v-model="form.capacity" style="width: 370px;" :step="1" :min="2"
                             :max="25" :precision="0"></el-input-number>
          </el-form-item>
          <el-form-item label="图类" prop="graphType">
            <el-select v-model="form.graphType" filterable placeholder="请选择" style="width: 370px;">
              <el-option
                v-for="item in dict.graph_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="自动获取数据">
            <el-switch v-model="form.automatic"></el-switch>
          </el-form-item>
          <el-form-item label="测试数据" v-if="!form.automatic">
            <el-input v-model="testData.length" style="width: 370px;" disabled/>
            <el-button @click="getDatalist(form.productCode,form.equipmentCode,form.testItem)" type="primary"
                       style="margin-left: 16px;">
              请选择
            </el-button>
          </el-form-item>
          <el-form-item label="数量条数" prop="quantity" v-if="form.automatic">
            <!--<el-input v-model="form.capacity" style="width: 370px;" />-->
            <el-input-number size="medium" v-model="form.quantity" style="width: 370px;" :step="1" :min="2"
                              :precision="0"></el-input-number>
          </el-form-item>
          <!--<el-form-item label="班组">-->
          <!--<el-input v-model="form.teamGroup" style="width: 370px;" />-->
          <!--</el-form-item>-->
        <!--  <el-form-item label="工单编号" prop="workOrderCode">
            <el-input v-model="form.workOrderCode" style="width: 370px; " disabled/>
          </el-form-item>-->
          <el-form-item label="规格上限" prop="specificationUpperLimit">
            <el-input v-model="form.specificationUpperLimit" style="width: 370px;" disabled/>
          </el-form-item>
          <el-form-item label="目标值" prop="targetValue">
            <el-input v-model="form.targetValue" style="width: 370px;" disabled/>
          </el-form-item>
          <el-form-item label="规格下限" prop="specificationFloor">
            <el-input v-model="form.specificationFloor" style="width: 370px;" disabled/>
          </el-form-item>
          <el-form-item label="判断规则">
            <el-input v-model="form.judgeRule" style="width: 370px;"/>
            <el-button @click="clickRegulation" type="primary"
                       style="margin-left: 16px;">
              请选择
            </el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
        <!--规则参数-->
        <el-dialog
          width="45%"
          title="异常判断规则"
          :visible.sync="innerVisible"
          append-to-body>
          <el-table :data="gridData" @row-dblclick="doubleClick" :row-class-name="tableRowClassName"
                    @selection-change="specificationChange" ref="regulationTable">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="80" property="coding" label="规则编号"></el-table-column>
            <el-table-column width="300" property="name" label="现行规则" :formatter="formattingData"></el-table-column>
            <el-table-column width="300" property="address" label="规则依据"></el-table-column>
          </el-table>
        </el-dialog>
        <el-drawer
          title="测试值"
          :append-to-body="true"
          :visible.sync="drawer" v-if='drawer' size="60%">
          <TestData :requestParameter="requestParameter" :testData.sync="testData"></TestData>
        </el-drawer>
        <!--规则参数-->
        <el-dialog
          width="25%"
          title="规则参数"
          :visible.sync="projecting"
          append-to-body>
          <el-form v-for="item in dataForm" label-width="80px">
            <el-form-item :label="item.name">
              <el-input v-model="gridData[item.index][item.name]"></el-input>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-dialog>


      <!--表格渲染-->

      <el-empty
        v-show="!crud.data || crud.data.length == 0"
        description="暂无数据"
      ></el-empty>
      <!--渲染列表-->
      <el-row
        :gutter="20"
        v-show="crud.data && crud.data.length > 0"
        v-loading="crud.loading"
      >
        <el-col :span="6" v-for="(item, index) in crud.data" :key="item.id">
          <div class="grid-content bg-purple">
            <el-card class="box-card">
              <div class="top">
                <img src="@/assets/images/cartogram.png" class="img" />
                <div class="content">
                  <div class="titleName">{{ item.name }}</div>
                  <div class="subTitle">图类: {{ dict.label.graph_type[item.graphType] }}</div>
                  <!--<div class="subTitle">产品型号: {{ item.productCode }}</div>-->
                  <div class="subTitle">判异规则: {{ item.judgeRule }}</div>
                  <div class="subTitle">
                    是否自动获取数据: {{item.automatic == true ? "是":"否"}}
                  </div>
                </div>
              </div>
              <div class="bottom">

                <el-button-group style="width: 85px;white-space:nowrap; ">

                  <router-link  :to="'/statistical/spc/chart/' + item.id">
                    <i class="el-icon-search button" title="查看"
                       style="cursor: pointer"></i>
                  </router-link>

                  <i class="el-icon-edit button"
                     v-permission="permission.edit" :loading="crud.status.cu === 2"  @click="crud.toEdit(item)"
                     style="cursor: pointer" title="编辑"></i>

                  <i class="el-icon-delete button"
                     style="cursor: pointer"
                     @click="toDelete(item)" title="删除"></i>
                </el-button-group>
                <div class="time">创建时间: {{ item.createTime }}</div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
  import crudSpcMain from '@/api/statistical/spcMain'
  import CRUD, {presenter, header, form, crud} from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'
  import crudProductModel from '@/api/product/productModel'
  import DateRangePicker from '@/components/DateRangePicker'
  import TestData from './testData'

  const defaultForm = {
    id: null,
    testItem: null,
    graphType: null,
    productCode: null,
    productName: null,
    capacity: null,
    teamGroup: null,
    equipmentCode: null,
    workOrderCode: null,
    specificationUpperLimit: null,
    targetValue: 0,
    specificationFloor: null,
    judgeRule: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    automatic:false,
    quantity:0
  }
  export default {
    name: 'StatisticalSpc',
    components: {pagination, crudOperation, rrOperation, udOperation, DateRangePicker,TestData},
    mixins: [presenter(), header(), form(defaultForm), crud()],
    dicts: ['graph_type'],
    cruds() {
      return CRUD({title: 'SPC统计图', url: 'api/spcMain', idField: 'id', sort: 'id,desc', crudMethod: {...crudSpcMain}})
    },
    data() {
      return {
        createTime: [this.getDate()+" 00:00:00", this.getDate()+" 23:59:59"],
        workOrderCode: "",
        productCode:"",
        deviceCode:"",
        paramCode:"",
        options: [],
        products: [],
        parameter: [],
        testData: [],
        specificationList: [],
        dataForm: [],
        drawer: false,
        innerVisible: false,
        projecting: false,
        automatic:false,
        requestParameter:null,
        permission: {
          add: ['admin', 'statisticalSpc:add'],
          edit: ['admin', 'statisticalSpc:edit'],
          del: ['admin', 'statisticalSpc:del']
        },
        rules: {
          productCode: [
            {required: true, message: '产品型号不能为空', trigger: 'blur'}
          ],
          testItem: [
            {required: true, message: '检测项目不能为空', trigger: 'blur'}
          ],
          graphType: [
            {required: true, message: '图类不能为空', trigger: 'blur'}
          ],
          equipmentCode: [
            {required: true, message: '设备不能为空', trigger: 'blur'}
          ],
          workOrderCode: [
            {required: true, message: '工单编号不能为空', trigger: 'blur'}
          ],
          specificationUpperLimit: [
            {required: true, message: '规格上限不能为空', trigger: 'blur'}
          ],
          targetValue: [
            {required: true, message: '目标值不能为空', trigger: 'blur'}
          ],
          specificationFloor: [
            {required: true, message: '规格下限不能为空', trigger: 'blur'}
          ],
          capacity: [
            {required: true, message: '样本容量不能为空', trigger: 'blur'}
          ],
          name: [
            {required: true, message: 'SPC名称不能为空', trigger: 'blur'}
          ],
        },
        queryTypeOptions: [
          {key: 'testItem', display_name: '检测项目'},
          {key: 'graphType', display_name: '图类'},
          {key: 'productCode', display_name: '产品型号'}
        ],
        tableData: [],
        gridData: [{
          coding: 'R0',
          name: '超出规格限制',
          address: '超出规格限制',
        }, {
          coding: 'R1',
          name: `{{n}}个点落在{{m}}倍sigma区以外`,
          address: '[n]个点落在[m]倍sigma区以外',
          n: 1,
          m: 3
        }, {
          coding: 'R2',
          name: '连续{{n}}点落在中心线同一侧',
          address: '连续[n]点落在中心线同一侧',
          n: 9
        }, {
          coding: 'R3',
          name: '连续{{n}}点递增或递减',
          address: '连续[n]点递增或递减',
          n: 6
        }, {
          coding: 'R4',
          name: '连续{{n}}点中相邻点交替上下',
          address: '连续[n]点中相邻点交替上下',
          n: 14
        }, {
          coding: 'R5',
          name: '连续{{n}}点中有{{m}}点落在中心线同一测的{{k}}倍sigma区以外',
          address: '连续[n]点中有[m]点落在中心线同一测的[k]倍sigma区以外',
          n: 3,
          m: 2,
          k: 2
        }, {
          coding: 'R6',
          name: '连续{{n}}点中有{{m}}点落在中心线同一侧的{{k}}倍sigma区以外',
          address: '连续[n]点中有[m]点落在中心线同一侧的[k]倍sigma区以外',
          n: 5,
          m: 4,
          k: 1
        }, {
          coding: 'R7',
          name: '连续{{n}}点落在中心线两侧的{{m}}倍sigma区内',
          address: '连续[n]点落在中心线两侧的[m]倍sigma区内',
          n: 15,
          m: 1
        }, {
          coding: 'R8',
          name: '连续{{n}}点落在中心线两侧且无一在{{m}}倍sigma区内',
          address: '连续[n]点落在中心线两侧且无一在[m]倍sigma区内',
          n: 8,
          m: 1
        },]
      }
    },
    methods: {
      // 钩子：在获取表格数据之前执行，false 则代表不获取数据
      [CRUD.HOOK.beforeSubmit]() {
        this.form.productName = this.$refs.selection.selectedLabel
        this.form.spcAbnormalRules = this.specificationList;
        this.form.spcDataCourseParams = this.testData;
        return true
      },
      //编辑前
      [CRUD.HOOK.beforeToEdit]() {
        //获取设备信息
        this.getEquipment(this.form.productCode, 1)
        //获取检测项目
        this.getTestItem(this.form.equipmentCode, 1)
        crudSpcMain.getRedact(this.form.id).then(res => {
          //获取测试数据
          this.testData = res.spcDataCourseParams
          //获取判断规则
          this.specificationList = res.spcAbnormalRules
        })
        return true
      },
      //新增编辑之后
      [CRUD.HOOK.beforeToAdd]() {
        this.specificationList = [];
        this.testData = []
        // location.reload()
      },
      //获取设备
      getEquipment(value, num) {
        crudSpcMain.getDevicename(value).then(res => {
          this.options = res
        })
        if (!num) {
          this.form.equipmentCode = '';
          this.form.testItem = '';
        }

      },
      //获取检测项目
      getTestItem(value, num) {
        crudSpcMain.getTestItem(value).then(res => {
          let nodes = [];
          if (res) {
            res.forEach(item => {
              nodes.push({
                value: item.paramCode,
                label: item.paramName,
                operationCode: item.operationCode,
                paramLower: item.paramLower,
                paramUpper: item.paramUpper,
                standard: item.standard,
                deviceCode: item.deviceCode
              });
            })
          }
          this.parameter = nodes;
        })
        if (!num) {
          this.form.testItem = '';
        }
      },
      //选中后回显上下限
      setBound(value) {
        this.parameter.forEach(item => {
          if (item.value === value) {
            this.form.specificationUpperLimit = item.paramUpper;
            this.form.targetValue = item.standard == undefined ? 0 : item.standard;
            this.form.specificationFloor = item.paramLower;
          }
        })
      },
      //获取测试数据
      getDatalist(productCode, equipmentCode, testItem) {
        if (!$.trim(productCode)) {
          this.$message.error('产品型号不能为空!');
          return
        }
        if (!$.trim(equipmentCode)) {
          this.$message.error('设备不能为空');
          return
        }
        if (!$.trim(testItem)) {
          this.$message.error('检测项目不能为空');
          return
        }
        this.productCode = productCode;
        this.deviceCode = equipmentCode;
        this.paramCode = testItem;
        var obj = {
          productCode: productCode,
          deviceCode: equipmentCode,
          paramCode: testItem,
          createTime:this.createTime,
        }
        this.requestParameter = obj
        this.drawer = true
      },
      //获取异常判断规则选中值
      specificationChange(val) {
        this.form.judgeRule = JSON.stringify(val.map(item => item.coding))
        this.specificationList = val;
      },
      tableRowClassName({row, rowIndex}) {
        row.index = rowIndex;
      },
      //双击事件
      doubleClick(row, column, event) {
        if (row.index === 0) {
          this.$message.error('没需要设置的规格参数!');
          return
        }
        this.dataForm = [];
        let arr = this.gridData[row.index]
        let numArr = ['n', 'm', 'k']
        numArr.forEach(f => {
          if (arr[f] != undefined) {
            let obj = {
              name: f,
              index: row.index
            }
            this.dataForm.push(obj)
          }
        })
        this.projecting = true;
      },
      //选择判断规则
      clickRegulation() {
        this.innerVisible = true;
        let specificationList = this.specificationList;
        //回显复选框
        this.$nextTick(() => {
          this.$refs.regulationTable.clearSelection();
          let list = []
          if (specificationList) {
            list = specificationList.map(item => item.coding)
            this.gridData.forEach((item) => {
              if (list.some(ele => ele == item.coding)) {
                specificationList.forEach(f => {
                  if (f.coding == item.coding) {
                    if (item.n != undefined) {
                      item.n = f.n;
                    }
                    if (item.m != undefined) {
                      item.m = f.m;
                    }
                    if (item.k != undefined) {
                      item.k = f.k;
                    }
                  }
                })
                this.$refs.regulationTable.toggleRowSelection(item, true)
              }
            })
          }
        })
      }
      ,
      //格式内容
      formattingData(row, column, cellValue, index) {
        let name = row.name
        return name.replace("{{n}}", this.gridData[index].n).replace("{{m}}", this.gridData[index].m).replace("{{k}}", this.gridData[index].k);
      },
      //跳转
      skip(id) {
        this.$router.push({path: '/statistical/spc/chart/' + id});
      }
      ,
      //查询
      inquire() {
        var obj = {
          paramCode:this.paramCode,
          createTime:this.createTime,
          workOrderCode:this.workOrderCode,
          deviceCode:this.deviceCode,
          productCode:this.productCode
        }
        this.getData(obj)
      },
      //获取当前时间
      getDate(){
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
      },
      // 确认删除
      toDelete(data) {
        this.$confirm("确认删除该数据吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.crud.doDelete(data);
          })
          .catch(() => {});
      }

    },

    mounted() {
      //关联产品
      crudProductModel.list().then(res => {
        this.products = res;
      });
    }
  }
</script>

<style scoped>
  .header-bottom {
    padding-bottom: 10px;
  }
  .el-card {
    margin-bottom: 15px;
  }

  .top {
    width: 100%;
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    justify-content: flex-start;
    align-items: flex-start;
    font-family: PingFangSC-Regular;
  }

  .img {
    width: 74px;
    margin-right: 15px;
  }

  .content {
    overflow: hidden;
    flex: 1 1;
  }

  .titleName {
    font-size: 14px;
    color: #333;
    line-height: 22px;
    font-weight: 700;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .subTitle {
    font-size: 12px;
    color: #555;
    line-height: 20px;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .descWrapper {
    font-size: 12px;
    color: #555;
    line-height: 20px;
    margin-bottom: 8px;
    display: flex;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .descContent {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    justify-content: flex-start;
  }
  .bottom .time {
    font-size: 13px;
    margin-left: 8px;
    color: #999;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }
  .bottom .button {
    font-size: 18px;
    padding: 0 2px;
  }
  .bottom .button:hover {
    color: #409eff;
  }
</style>
